package cmd

import (
	"context"
	"fmt"
	"github.com/kevinlisr/install-levault/conf"
	"github.com/kevinlisr/install-levault/service"
	"github.com/kevinlisr/install-levault/vari"
	"github.com/spf13/cobra"
)

// 二级命令
var dmdbCmd = &cobra.Command{
	Use:   "dm",
	Short: "dm [query/update/download]",
	Long: `Creates the bucket with specified name
            use: minio create bucket -n testbucket
                 minio upload -u http://127.0.0.1:9000 -b testbucket -d /data/testdir`,
	RunE: func(cmd *cobra.Command, args []string) error {
		return nil
	},
}

// 三级命令
var downloadCmd = &cobra.Command{
	Use:   "download",
	Short: "Download file from minio",
	Long: `Queries the file name in the URL from the DM database 
			and downloads the file from the specified minio to the specified directory`,
	RunE: func(cmd *cobra.Command, args []string) error {
		// 初始化全局变量
		if err := loadGlobalConfig(ConfType, Format); err != nil {
			return fmt.Errorf("LoadGlobalConfig failed %s\n", ConfFile)
		}

		// 获取config配置
		conf := conf.C()
		vari.Logger.Info(fmt.Sprintf("The schema: %s url: %s\n", conf.Dmdb.Schema, conf.Dmdb.Tables))

		// 获取达梦DB
		db, err := conf.Dmdb.GetDmDB()
		if err != nil {
			vari.Logger.Error(fmt.Sprintf("Get DmDB failed %s\n", conf.Dmdb.DataSource))
			return fmt.Errorf("Get DmDB failed %s\n", conf.Dmdb.DataSource)
		}
		vari.Logger.Info(fmt.Sprintf("Get DmDB Success %s\n", conf.Dmdb.DataSource))

		// Get minio client
		minioClient, err := conf.Minio.Client()
		if err != nil {
			vari.Logger.Error(fmt.Sprintf("Get minio %s client failed!", conf.Minio.EndpointUrl))
			return fmt.Errorf(fmt.Sprintf("Get minio %s client failed!", conf.Minio.EndpointUrl))
		}

		// Get minio executor
		minioExec := service.NewMinioExecutor(minioClient)

		// Get Dm executor and loop download files from minio
		dmDbExec := service.NewDmDbExecutor()
		ctx := context.Background()
		if err = dmDbExec.DownloadMinioFile(ctx, db, minioExec, conf.Dmdb.Tables, conf.Dmdb.Schema, FilePath); err != nil {
			vari.Logger.Error("Loop Download Minio File failed, " + err.Error())
			return err
		}
		return nil
	},
}

// 三级命令
var updateCmd = &cobra.Command{
	Use:   "update",
	Short: "Updates the value of the specified field in the DM database",
	Long: `Updates the specified data in the DM database, 
            You need to modify the value in the config.yaml.`,
	RunE: func(cmd *cobra.Command, args []string) error {
		// 初始化全局变量
		if err := loadGlobalConfig(ConfType, Format); err != nil {
			return fmt.Errorf("LoadGlobalConfig failed %s\n", ConfFile)
		}

		// 获取config配置
		conf := conf.C()
		vari.Logger.Info(fmt.Sprintf("The schema: %s url: %s", conf.Dmdb.Schema))

		// 获取达梦DB
		db, err := conf.Dmdb.GetDmDB()
		if err != nil {
			vari.Logger.Error(fmt.Sprintf("Get DmDB failed %s\n", conf.Dmdb.DataSource))
			return fmt.Errorf("Get DmDB failed %s\n", conf.Dmdb.DataSource)
		}
		vari.Logger.Info(fmt.Sprintf("Get DmDB Success %s", conf.Dmdb.DataSource))

		// Get Dm executor and loop download files from minio
		dmDbExec := service.NewDmDbExecutor()

		//db *sql.DB, dmlsqls []string, url string, username string,
		//	pwd string, dbtype string, host string, port string, miniourlOld string, miniourlNew string
		if err = dmDbExec.UpdateTable(db, conf.Updatedm.Dmlsqls, conf.Updatedm.Dburl, conf.Updatedm.Username, conf.Updatedm.Password, conf.Updatedm.Dbtype,
			conf.Updatedm.Host, conf.Updatedm.Port, conf.Updatedm.MiniourlOld, conf.Updatedm.MiniourlNew); err != nil {
			vari.Logger.Error(err.Error())
			return err
		}

		return nil
	},
}

func init() {
	RootCmd.AddCommand(dmdbCmd)
	dmdbCmd.AddCommand(downloadCmd, updateCmd)

	downloadCmd.PersistentFlags().StringVarP(&ConfType, "config-type", "t", "file", "the service config type [file/env/etcd], dm download -t file ")
	downloadCmd.PersistentFlags().StringVarP(&ConfFile, "config-file", "f", "etc/config.toml", "the service config from file, dm download -f /root/config.toml")
	downloadCmd.PersistentFlags().StringVarP(&Format, "format", "m", "yaml", "dm download -m yaml")
	downloadCmd.PersistentFlags().StringVarP(&EndpointUrl, "endpointurl", "e", "endpointurl", "dm download -e http://127.0.0.1:9000")
	downloadCmd.PersistentFlags().StringVarP(&Schema, "schema", "s", "LEVAULT", "dm download -s TEST")
	downloadCmd.PersistentFlags().StringVarP(&FilePath, "file-path", "d", "/tmp/", "dm download -d /tmp/")

	updateCmd.PersistentFlags().StringVarP(&ConfType, "config-type", "t", "file", "the service config type [file/env/etcd], dm update -t file ")
	updateCmd.PersistentFlags().StringVarP(&ConfFile, "config-file", "f", "etc/config.toml", "the service config from file, dm update -f /root/config.toml")
	updateCmd.PersistentFlags().StringVarP(&Format, "format", "m", "yaml", "dm update -m yaml")
	updateCmd.PersistentFlags().StringVarP(&Schema, "schema", "s", "LEVAULT", "dm update -s TEST")
}
